package com.masterclient.app.modules.shop;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.core.LogisticsCenter;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselibrary.bean.shop.DealerProductItemBean;
import com.eoner.baselibrary.bean.shop.DealerProductManagerData;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.commonbean.product.ShareProductDataBean;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.modules.goods.beans.ShareProductBean;
import com.masterclient.app.modules.shop.adapter.DealerProductManagerAdapter;
import com.masterclient.app.modules.shop.contract.DealerProductManagerContract;
import com.masterclient.app.modules.shop.contract.DealerProductManagerPresenter;
import com.masterclient.app.widget.ShareCommonDialog;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;

/**
 * @auther hjian
 * @date 2020/9/11.
 */
public class DealerProductManagerFragment extends BaseFragment<DealerProductManagerPresenter>
        implements DealerProductManagerContract.View {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;

    private int page,status,clickPos,productType;;
    private View headView, emptyView;
    private TextView headContentView;
    private DealerProductManagerAdapter managerAdapter;
    private boolean isContinuous = false;//列表分享
    private boolean isFirst = true;
    private boolean isShowNotice = true;

    public static DealerProductManagerFragment newInstance(int status,int productType) {
        Bundle bundle = new Bundle();
        bundle.putInt("status", status);
        bundle.putInt("productType", productType);
        DealerProductManagerFragment fragment = new DealerProductManagerFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_recycler_refresh, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        page = 1;
        status = getArguments().getInt("status");
        productType = getArguments().getInt("productType");

        recyclerView.setPadding(ScreenUtils.dp2px(16),ScreenUtils.dp2px(10),ScreenUtils.dp2px(16),0);
        emptyView = View.inflate(mContext,R.layout.empty_recycler,null);
        ((TextView)emptyView.findViewById(R.id.empty_title)).setTextColor(Color.parseColor("#C2C5CC"));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = ScreenUtils.dp2px(10);

            }
        });
        managerAdapter = new DealerProductManagerAdapter();
        headView = View.inflate(getActivity(), R.layout.head_dealer_product_manager, null);
        headContentView = headView.findViewById(R.id.head_dealer_manager_text);
        View headCloseView = headView.findViewById(R.id.head_dealer_manager_close);
        View headNewsView = headView.findViewById(R.id.head_dealer_manager_icon);
        managerAdapter.addHeaderView(headView);
        if (productType == 3){
            headNewsView.setVisibility(View.GONE);
            headCloseView.setVisibility(View.VISIBLE);
            headCloseView.setOnClickListener(v -> {
                isShowNotice = false;
                managerAdapter.removeAllHeaderView();
            });
        }else {
            headNewsView.setVisibility(View.VISIBLE);
            headCloseView.setVisibility(View.GONE);
        }

        managerAdapter.setEmptyView(emptyView);
        emptyView.setVisibility(View.GONE);

        recyclerView.setAdapter(managerAdapter);

        refreshData(1);
        initListener();
    }

    private void initListener() {
        swipeLayout.setOnRefreshListener(() -> refreshData(1));

        managerAdapter.setOnLoadMoreListener(() -> refreshData(page),recyclerView);

        managerAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            clickPos = position;
            DealerProductItemBean bean = managerAdapter.getData().get(position);
            switch (view.getId()){
                case R.id.item_dealer_manager_preview:
                case R.id.item_dealer_manager_image:
                    if (!"2".equals(managerAdapter.getData().get(position).getStatus())) {
                        ARouter.getInstance().build(AroutePath.COMMODITY_DETAIL_ACTIVITY)
                                .withBoolean("isFormDealer", true)
                                .withString("id", managerAdapter.getData().get(position).getProduct_id())
                                .withString("source_position", position + "").navigation();
                    }
                    break;
                case R.id.item_dealer_manager_stroke:
                case R.id.view_stock:
                    ARouter.getInstance().build(FCRouterPath.STOCK_SET_PATH)
                            .withString("productId",bean.getProduct_id())
                            .navigation();
                    break;
                case R.id.item_dealer_manager_shipping:
                case R.id.item_dealer_manager_desc:
                case R.id.item_dealer_other_manager_desc:
                    Postcard postcard = ARouter.getInstance().build(AroutePath.DEALER_SHIPPING_LIST_ACTIVITY)
                            .withString("product_id", bean.getProduct_id())
                            .withString("delivery_id",bean.getDelivery_id());
                    LogisticsCenter.completion(postcard);
                    Intent intent = new Intent(getContext(), postcard.getDestination());
                    intent.putExtras(postcard.getExtras());
                    getActivity().startActivityFromFragment(DealerProductManagerFragment.this,intent,0x97);
                    break;
                case R.id.item_dealer_manager_share:
                    if (isContinuous) return;
                    isContinuous = true;
                    mPresenter.getProductShare(bean.getProduct_id());
                    break;
                default:
            }
        });
    }

    public void refreshData(int page){
        if (page == 1){
            recyclerView.stopScroll();
            recyclerView.scrollToPosition(0);
        }
        this.page = page;
        mPresenter.getProductList(String.valueOf(status), page,String.valueOf(productType));
    }

    @Override
    public void showData(DealerProductManagerData dataBean) {

        if (swipeLayout.isRefreshing()){
            swipeLayout.setRefreshing(false);
        }
        managerAdapter.loadMoreComplete();
        if (page == 1){
            if (isShowNotice&&!TextUtils.isEmpty(dataBean.getTitle_info())){
                headContentView.setText(dataBean.getTitle_info());
                if (managerAdapter.getHeaderLayoutCount()<=0){
                    managerAdapter.addHeaderView(headView);
                }
            }else {
                managerAdapter.removeAllHeaderView();
            }


            if (dataBean.getList() != null){
                managerAdapter.setNewData(dataBean.getList());
                ((DealerProductManagerActivity)getActivity()).setTabName(productType-2, String.valueOf((productType ==2?dataBean.getOnsale_total():dataBean.getOffsale_total())),productType);
            }
            if (productType == 2){
                ((TextView)emptyView.findViewById(R.id.empty_title)).setText("暂时没有经销商品");
            }else {
                ((TextView)emptyView.findViewById(R.id.empty_title)).setText("暂时没有轻创商品");
            }
            emptyView.setVisibility(dataBean.getList() == null
                    || dataBean.getList().size() == 0 ?View.VISIBLE:View.GONE);

        }else {
            managerAdapter.addData(dataBean.getList());
        }


        if(dataBean.getList() == null || dataBean.getList().size()<1 || managerAdapter.getData().size()>=(productType ==2?dataBean.getOnsale_total():dataBean.getOffsale_total())){
            managerAdapter.setEnableLoadMore(false);
        }else {
            ++page;
        }
        isFirst = false;
    }

    @Override
    public void showDataFailed(String msg) {
        ToastUtil.showToast(msg);
        if (swipeLayout.isRefreshing()){
            swipeLayout.setRefreshing(false);
        }
        managerAdapter.loadMoreComplete();
    }

    @Override
    public void showShareData(boolean isSuccess, ShareProductDataBean shareData) {
        isContinuous = false;
        if (isSuccess){
            String max_commission = shareData.getMax_commission();
            if (Float.parseFloat(shareData.getMax_double_commission()) > Float.parseFloat(max_commission)) {
                max_commission = shareData.getMax_double_commission();
            }
            ShareProductDataBean.ShareBean shareMessage = shareData.getShare();
            ShareCommonDialog shareComDialog = new ShareCommonDialog(getActivity());
            shareComDialog.show();
            String product_type = shareData.getProduct_type();
            shareComDialog.setSData("商品","",managerAdapter.getData().get(clickPos).getProduct_id(),shareData.getShare().getTitle() ,"",shareData.getShare().getUrl());
            shareComDialog.setShareData(shareMessage.getTitle(), shareMessage.getUrl(),
                    shareMessage.getDesc(), managerAdapter.getData().get(clickPos).getImage(), shareMessage.getJump_type()
                    , shareMessage.getPath(), shareMessage.getMini_program_image());
            shareComDialog.setProduct_type(Integer.parseInt(product_type));
            shareComDialog.setCommission(("4".equals(product_type) || "3".equals(product_type)
                            || "2".equals(product_type)) ? "0" :
                            shareData.getCommission(),
                    max_commission);
            shareComDialog.shareGoodsDetail(new ShareProductBean(shareData.getPrice(),shareData.getIntegral_price(),shareData.getPrice_tag().getMarket_price_tag()
                    ,shareData.getMarket_price(),shareData.getPrice_tag().getBase_price_tag(),shareData.getDaily_price(),shareData.getPrice_tag().getActivity_price_tag(),product_type));
            shareComDialog.setOnlyPicShare();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x97 && resultCode == RESULT_OK){
            if (managerAdapter != null){
                DealerProductItemBean bean = managerAdapter.getData().get(clickPos);
                bean.setDelivery_id(data.getStringExtra("delivery_id"));
                bean.setDelivery_name(data.getStringExtra("delivery_name"));
                managerAdapter.notifyDataSetChanged();
            }
        }
    }
}
